﻿using System.Text;
using System.Web;
using System.Web.Mvc;
using TDF.Core.Json;
using TDF.Core.Models;
using System.Collections.Generic;

namespace ARchGL.Declaration.Platform.Web.Controllers
{
    /// <summary>
    /// 前端BootstrapTable数据模型
    /// </summary>
    public class BootstrapTableModel : ActionResult
    {
        /// <summary>
        /// 
        /// </summary>
        public long total { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public object rows { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            WriteToResponse(response);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        public void WriteToResponse(HttpResponseBase response)
        {
            response.ContentType = "application/json";
            response.ContentEncoding = Encoding.UTF8;
            response.Write(this.ToJson());
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public static class BootstrapTableModelExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pagedList"></param>
        /// <returns></returns>
        public static BootstrapTableModel ToBootstrapTableModel<T>(this IPagedList<T> pagedList) where T : class
        {
            return new BootstrapTableModel()
            {
                rows = pagedList.Rows ?? new List<T>(),
                total = pagedList.TotalCount
            };
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static BootstrapTableModel ToBootstrapTableModel<T>(this IList<T> list) where T : IDto
        {
            return new BootstrapTableModel()
            {
                rows = list ?? new List<T>(),
                total = list.Count
            };
        }
    }
}